#include "stdafx.h"
#include "Viewer.h"
#include <math.h>

const float Viewer::speed = 0.1;
Viewer::Viewer(){
}
Viewer::Viewer(int width, int height, int tWidth, int tHeight, GameMap* gm)
{
	this->width = width;
	this->height = height;
	g = gm;
	
	lookAt = LookAt((float)tWidth/2,(float) tHeight, height);

	int h = g->getHeightAt(tWidth/2, tHeight/2)+1;
	eye = Eye(tWidth/2, h, tHeight/2);
	pitch = 0; 
	yaw = 180; 
	mouseY = height/2;
	mouseX = width/2;
	SetCursorPos(width/2, height/2);
	aKey = false;
	sKey = false;
	wKey = false;
	dKey= false;
	setViewMatrix();
}
void Viewer::setViewMatrix(){
	tick();
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	//gluLookAt(	64.0f, 0.0f, 64.0f,
	//			64.0f, 64.0f, 0.0f,
	//			0.0f,0.0f, 1.0f);


	GLfloat h = g->getHeightAt(eye.X,eye.Z)+2;
	glRotatef(pitch, 1.0f, 0.0f, 0.0f);
	glRotatef(yaw, 0.0f, 1.0f, 0.0f);
	glTranslatef(-eye.X, -h, -eye.Z); 
	
}

void Viewer::tick(){
	int xPos = 0, yPos = 0;
	int moveY = 0, moveX = 0;
	
	CURSORINFO* info = new CURSORINFO();
	info->cbSize = sizeof(CURSORINFO);
	GetCursorInfo(info);
	xPos= info->ptScreenPos.x;
	yPos = info->ptScreenPos.y;

	moveX = (xPos - mouseX)/10;
	moveY = (yPos - mouseY)/10 ;
	yaw =  (yaw + moveX) % 360;
	pitch = min(max(pitch+moveY,-90.0f),90.0f);
	SetCursorPos(width/2, height/2);
	if (wKey)
	{
		eye.Z -= (float) cos((float) yaw * 3.1415/180) *  speed;
		eye.X += (float) sin((float) yaw * 3.1415/180) *  speed;
	}

	if (sKey)
	{
		eye.Z += (float) cos((float) yaw * 3.1415/180) *  speed;
		eye.X -= (float) sin((float) yaw * 3.1415/180) *  speed;
	}

	if (dKey)
	{
		eye.Z += (float) cos((float) (yaw-90) * 3.1415/180) *  speed;
		eye.X -= (float) sin((float) (yaw-90) * 3.1415/180) *  speed;
	}

	if (aKey)
	{
		eye.Z += (float) cos((float) (yaw+90) * 3.1415/180) *  speed;
		eye.X -= (float) sin((float) (yaw+90) * 3.1415/180) *  speed;
	}

}
LRESULT Viewer::handle(Window &wnd, UINT msg, HWND hwnd, long param1, long param2){
	int zDelta = 0;
	switch(msg){
	case WM_MOUSEWHEEL:
		zDelta = GET_WHEEL_DELTA_WPARAM(param1);
		return DefWindowProc(hwnd,msg,param1,param2);
		break;
	case WM_KEYDOWN:
		switch(param1){
		case 0x41:
			aKey = true;
			break;
		case 0x44:
			dKey = true;
			break;
		case 0x57:
			wKey = true;
			break;
		case 0x53:
			sKey = true;
			break;
		}
	break;
	case WM_KEYUP:
		switch (param1){
		case 0x41:
			aKey = false;
			break;
		case 0x44:
			dKey = false;
			break;
		case 0x57:
			wKey = false;
			break;
		case 0x53:
			sKey = false;
			break;
		}
	break;
	}
	return DefWindowProc(hwnd,msg,param1,param2);
}


Viewer::~Viewer(void)
{
}
void Viewer::draw(){
}
